﻿using System;
using System.Collections.Generic;

namespace Affinity.Core.Messages
{
    public class ChannelReaderGroup : IDisposable
    {
        public void AddFor<TMessage>(IReadableChannel<TMessage> channel, MessageSentHandler<TMessage> messageHandler)
        {
            _ChannelReaders.Add(ChannelReader.Create(channel, messageHandler));
        }

        public void Dispose()
        {
            RemoveAll();
        }

        public void RemoveFor<TMessage>(IReadableChannel<TMessage> channel, MessageSentHandler<TMessage> messageHandler = null)
        {
            lock (_ChannelReadersLock) 
            {
                foreach (ChannelReader channelReader in _ChannelReaders.ToArray())
                {
                    if (ChannelReader.Match(channelReader, channel, messageHandler)) _ChannelReaders.Remove(channelReader);
                }                    
            }
        }

        public void RemoveAll()
        {
            ChannelReader[] channelReaders = null;

            lock (_ChannelReadersLock)
            {
                channelReaders = _ChannelReaders.ToArray();
                _ChannelReaders.Clear();
            }

            foreach (ChannelReader channelReader in channelReaders) channelReader.Dispose();
        }

        private List<ChannelReader> _ChannelReaders = new List<ChannelReader>();
        private object _ChannelReadersLock = new object();
    }
}
